﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.ComponentModel;
using System.Reflection;

namespace BPMS.Utility
{
    public class EnumHelper
    {
        /// <summary>
        /// 获取枚举的描述信息
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static String GetEnumDesc(Enum e)
        {
            if (e == null)
                return "";

            FieldInfo EnumInfo = e.GetType().GetField(e.ToString());
            if (EnumInfo == null)
                return e.ToString();

            DescriptionAttribute[] EnumAttributes
                = (DescriptionAttribute[])EnumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (EnumAttributes.Length > 0)
            {
                return EnumAttributes[0].Description;
            }
            return e.ToString();

        }

        /// <summary>
        /// 获取枚举的描述信息，根据传入的枚举值
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static String GetEnumDesc(System.Type enumType, int enumValue)
        {
            string result = "";
            foreach (object enumObject in Enum.GetValues(enumType))
            {
                Enum e = (Enum)enumObject;
                if (Convert.ToInt32(e) == enumValue)
                {
                    result = GetEnumDesc(e);
                    break;
                }
            }

            return result;

        }

        /// <summary>
        /// 将含有描述信息的枚举绑定到字典中
        /// </summary>
        /// <param name="listControl"></param>
        /// <param name="enumType"></param>
        public static Dictionary<string, int> GetEnumKeyInt(System.Type enumType)
        {
            Dictionary<string, int> dicEnum = new Dictionary<string, int>();
            foreach (object enumValue in Enum.GetValues(enumType))
            {
                Enum e = (Enum)enumValue;
                dicEnum.Add(GetEnumDesc(e), Convert.ToInt32(enumValue));
            }
            return dicEnum;
        }
        /// <summary>
        /// 将含有描述信息的枚举组装datatable(Table两个字段，text是描述，value是值(默认是int的值))
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static DataTable GetEnumTable(System.Type enumType)
        {
            DataTable dt = new DataTable();
            DataRow dr = null;
            dt.Columns.Add("Text");
            dt.Columns.Add("Value");
            foreach (object enumValue in Enum.GetValues(enumType))
            {
                dr = dt.NewRow();
                Enum e = (Enum)enumValue;
                dr["Text"] = GetEnumDesc(e);
                dr["Value"] = Convert.ToInt32(enumValue).ToString();
                dt.Rows.Add(dr);
            }
            return dt;
        }
    }
}
